/**
 * Created by Ysssssss on 21/3/3.
 */

import apiType, {
    GET_AREA_JSON,
    SET_HEADER_BUTTON_INFO,
    SET_HEADER_BREAD_CRUMB_INFO
} from "@constants/ActionTypes";

const initialState = {
    buttonInfo: null,
    breadcrumbInfo: null,
    cascaderList: null,
    areaMap: null
}

export default function update(state = initialState, action) {
    const { response, params, payload } = action
    switch (action.type) {
        case SET_HEADER_BUTTON_INFO:
            return {
                ...state,
                buttonInfo: payload?.buttonInfo
            }
        case SET_HEADER_BREAD_CRUMB_INFO:
            return {
                ...state,
                breadcrumbInfo: payload?.breadcrumbInfo
            }
        case apiType(GET_AREA_JSON).success:
            const _cascaderList = []
            const cascaderCityMap = {}
            const cascaderCountyMap = {}
            for (let key in response.county_list) {
                let _key = `${key}`.slice(0,4)
                if (!cascaderCountyMap[_key]) {
                    cascaderCountyMap[_key] = []
                }
                cascaderCountyMap[_key].push({
                    value: key,
                    label: response.county_list[key]
                })
            }
            for (let key in response.city_list) {
                let _key = `${key}`.slice(0,2)
                if (!cascaderCityMap[_key]) {
                    cascaderCityMap[_key] = []
                }
                cascaderCityMap[_key].push({
                    value: key,
                    label: response.city_list[key],
                    ...(cascaderCountyMap[`${key}`.slice(0,4)] ? {
                        children: cascaderCountyMap[`${key}`.slice(0,4)]
                    } : {})
                })
            }
            for (let key in response.province_list) {
                _cascaderList.push({
                    value: key,
                    label: response.province_list[key],
                    ...(cascaderCityMap[`${key}`.slice(0,2)] ? {
                        children: cascaderCityMap[`${key}`.slice(0,2)]
                    } : {})

                })
            }
            return {
                ...state,
                cascaderList: _cascaderList,
                areaMap:{
                    ...response.province_list,
                    ...response.city_list,
                    ...response.county_list
                }
            }
        default:
            return state
    }
}